<!-- 个人资料 -->
<template>
  <view>
    <aster-back font-color="#333" :show-title="true" title="个人资料" />
    <view class="border-radius margin-top-sm">
      <aster-list-title title="头像" iconfont="" @goto="showAvatar()">
        <uni-file-picker
          v-model="avatar"
          :limit="1"
          :del-icon="false"
          :imageStyles="imageStyles"
          :auto-upload="true"
          disable-preview
          file-mediatype="image"
          @select="selectImage"
        />
      </aster-list-title>
    </view>
    <view class="gap" />
    <view class="border-radius margin-top-sm">
      <aster-list-title title="昵称" iconfont="" :tip="userInfo?.nickname" @goto="showNickname()" />
      <aster-list-title
        title="个性签名"
        iconfont=""
        :tip="userInfo?.signature"
        @goto="showSignature()"
      />
    </view>
    <view class="gap" />
    <view class="border-radius margin-top-sm">
      <aster-list-title title="性别" iconfont="" :tip="gender" @click="showGender()" />
      <aster-list-title
        title="生日"
        iconfont=""
        :tip="userInfo?.birthday"
        @click="showBirthday()"
      />
      <aster-list-title title="地区" iconfont="" :tip="area" @click="() => (showArea = true)" />
    </view>

    <popup-dialog
      :show="showPopup"
      bgColor="#fff"
      :title="popupParams.title"
      :content="popupParams.content"
      :tip="popupParams.tip"
      :maxlength="popupParams.maxlength"
      @cancel="popupParams.cancel"
      @confirm="popupParams.confirm"
    />

    <aster-action-sheet
      :show="showGenderSheet"
      :list="genderList"
      :round="20"
      @close="closeGender()"
      @select="selectGender"
    />

    <aster-picker
      :show="showPicker"
      ref="asterPickerRef"
      :columns="pickerParams.columns"
      :default-index="pickerParams.defaultIndex"
      :suffixs="pickerParams.suffixs"
      @cancel="pickerParams.cancel"
      @confirm="pickerParams.confirm"
      @change="pickerParams.change"
    />

    <aster-area
      :show="showArea"
      :default-value="userInfo?.area"
      @confirm="area_confirm"
      @cancel="area_cancel"
    />
  </view>
</template>
<script setup lang="ts">
  import AsterBack from '@/components/common/aster-back.vue';
  import PopupDialog from '@/components/popup/popup-dialog.vue';
  import AsterListTitle from '@/components/common/aster-list-title.vue';
  import AsterActionSheet from '@/components/common/aster-action-sheet.vue';
  import AsterPicker from '@/components/common/aster-picker.vue';
  import AsterArea from '@/components/area/aster-area.vue';
  import {
    editNickname,
    editSignature,
    editGender,
    editBirthday,
    editArea,
    editAvatar,
  } from '@/services/api/user/user';
  import { UserInfoModel } from '@/services/model/userModel';
  import { Modal, Toast } from '@/utils/uniapi/prompt';
  import { onLoad } from '@dcloudio/uni-app';
  import { computed, reactive, ref } from 'vue';
  import { currentYear, daysInMonth, fillZero, intervalYear } from '@/utils/dateUtils';
  import { areaList } from '@vant/area-data';
  import { area_list, area_text } from '@/utils';
  import { isEmpty, isNotEmpty } from '@/utils/is';
  import { FileModel, FilePickerModel } from '@/services/model/fileModel';
  import { uploadImages } from '@/utils/fileUtils';
  import { getCache } from '@/utils/cache';
  import { USER_INFO_KEY } from '@/enums/cacheEnum';
  import { ResultEnum } from '@/enums/httpEnum';

  const userInfo = ref<UserInfoModel>();

  onLoad(() => {
    userInfo.value = getCache(USER_INFO_KEY);
  });

  // 默认头像
  const base64Avatar =
    '';
  // 头像样式
  const imageStyles = {
    width: 48,
    height: 48,
    border: {
      radius: '50%',
    },
  };
  /** 监听头像 */
  const avatar = computed(() => {
    const url = isNotEmpty(userInfo.value?.area) ? userInfo.value?.area : base64Avatar;
    return { uuid: Date.now(), name: 'avatar.jpg', extname: 'jpg', url: url };
  });
  const selectImage = (e: FilePickerModel) => {
    if (e.tempFiles) {
      const uploadFiles = e.tempFiles.map((item: FileModel) => {
        return {
          name: item.name,
          file: item.file,
          uri: item.url,
        };
      });
      // 上传图片
      uploadImages(uploadFiles, changeAvatar);
    }
  };
  const changeAvatar = (file: FileModel) => {
    editAvatar(file.url).then(({ data }) => {
      if (data.code === ResultEnum.SUCCESS) {
        Toast('保存成功!');
        if (userInfo.value) userInfo.value.avatar = file.url;
      }
    });
  };

  //TODO 添加到字典中
  const genderList = ref([
    { name: '男', value: 'M' },
    { name: '女', value: 'F' },
    { name: '未知', value: 'U' },
  ]);
  /** 性别 */
  const gender = computed(() => {
    let arr = genderList.value.filter((item) => item.value == userInfo.value?.gender);
    return arr[0]?.name;
  });
  /** 地区 */
  const area = computed(() => {
    if (userInfo.value && !isEmpty(userInfo.value.area)) {
      return area_text(userInfo.value.area, area_list(areaList));
    }
    return '-';
  });

  const showAvatar = () => {};

  /** 修改昵称 */
  const showNickname = () => {
    Modal({
      title: '修改昵称',
      content: userInfo.value?.nickname,
      editable: true,
    }).then((res: any) => {
      if (res.confirm) {
        editNickname(res.content).then(({ data }) => {
          if (data.code === ResultEnum.SUCCESS) {
            if (userInfo.value) userInfo.value.nickname = res.content;
          }
        });
      }
      if (res.cancel) {
        console.log('close');
      }
    });
  };

  // 弹出层
  const showPopup = ref(false);
  const popupParams = reactive({
    title: '',
    content: '',
    type: '',
    tip: '',
    maxlength: 20,
    cancel: () => {
      showPopup.value = false;
    },
    confirm: (e: any) => {
      console.log(e);
    },
  });

  // 选择器
  const asterPickerRef = ref();
  const showPicker = ref(false);
  const pickerParams = reactive({
    // 每一列的数据
    columns: <any[]>[],
    // 加载状态
    loading: false,
    // 每列中可见选项的数量
    visibleItemCount: 5,
    // 自定义需要展示的text属性键名
    keyName: 'name',
    // 各列默认值的索引
    defaultIndex: <number[]>[],
    // 各列的后缀值
    suffixs: <string[]>[],
    // 点击取消按钮
    cancel: () => {
      showPicker.value = false;
    },
    // 点击确定按钮
    confirm: (e: any) => {
      console.log('confirm--->', e);
      showPicker.value = false;
    },
    // 当选择值变化时触发
    change: (e: any) => {
      console.log('confirm--->', e);
    },
  });

  // 个性签名
  const showSignature = () => {
    popupParams.title = '个性签名';
    popupParams.content = userInfo.value?.signature ? userInfo.value?.signature : '';
    popupParams.tip = '4-20个字符';
    popupParams.maxlength = 20;
    popupParams.confirm = (content: string) => {
      editSignature(content).then(({ data }) => {
        if (data.code === ResultEnum.SUCCESS) {
          if (userInfo.value) userInfo.value.signature = content;
          showPopup.value = false;
        }
      });
    };
    showPopup.value = true;
  };

  // 性别
  const showGenderSheet = ref<boolean>(false);
  const showGender = () => {
    console.log('123');
    showGenderSheet.value = true;
  };
  const selectGender = (item: any) => {
    editGender(item.value).then(({ data }) => {
      if (data.code === ResultEnum.SUCCESS) {
        if (userInfo.value) userInfo.value.gender = item.value;
        closeGender();
      }
    });
  };
  const closeGender = () => {
    showGenderSheet.value = false;
  };

  // 生日
  const showBirthday = () => {
    let year = intervalYear(currentYear());
    let month = [
      { name: 1 },
      { name: 2 },
      { name: 3 },
      { name: 4 },
      { name: 5 },
      { name: 6 },
      { name: 7 },
      { name: 8 },
      { name: 9 },
      { name: 10 },
      { name: 11 },
      { name: 12 },
    ];
    let day = daysInMonth(currentYear(), 1);
    // 各列数据
    pickerParams.columns = [];
    pickerParams.columns.push(year);
    pickerParams.columns.push(month);
    pickerParams.columns.push(day);
    // 各列默认值索引
    pickerParams.defaultIndex = [0, 0, 0];
    year.forEach((item: any, index) => {
      if (item.name == currentYear()) {
        pickerParams.defaultIndex[0] = index;
      }
    });
    pickerParams.suffixs = ['年', '月', '日'];
    pickerParams.confirm = (e: any) => {
      console.log('confirm', e);
      const value = e.value;
      let birthday = value[0].name + '-' + fillZero(value[1].name) + '-' + fillZero(value[2].name);
      editBirthday(birthday).then(({ data }) => {
        if (data.code === ResultEnum.SUCCESS) {
          if (userInfo.value) userInfo.value.birthday = birthday;
          showPicker.value = false;
        }
      });
    };
    pickerParams.change = (e: any) => {
      if (e.columnIndex.value == 1) {
        let columns = daysInMonth(e.value[0].name, e.value[1].name);
        asterPickerRef.value.setColumnValues(2, columns);
      }
    };
    showPicker.value = true;
  };

  /** 地区 */
  const showArea = ref(false);
  const area_confirm = (e: any) => {
    editArea(e.value[2].value).then(({ data }) => {
      if (data.code === ResultEnum.SUCCESS) {
        if (userInfo.value) userInfo.value.area = e.value[2].value;
        showArea.value = false;
      }
    });
  };
  const area_cancel = (e: any) => {
    showArea.value = false;
  };
</script>
<style lang="scss">
  page {
    padding: 0 20rpx;
  }

  .popup {
    padding: 20rpx;
  }
</style>
